<?php
/*
 * 拿到总数
*/
function get_total($table, $id, $foreign_key){
	$format = '';
	$format = "SELECT count(`id`) AS `total` FROM {$table} ";
	$format .=" WHERE  `{$foreign_key}`=?  ";
	
	$res = db::execute($format, array($id));
	
	return intval($res[0]['total']) ? intval($res[0]['total']): 0;
}

/*
 * 拿到列表
 */
function get_list($table, $foreign_key, $id, $pag, $limit) {
	$start = ($pag-1)*$limit;
	$format = "SELECT * FROM  {$table} WHERE `{$foreign_key}`=? ";
	$format .=" ORDER BY `createtime` DESC LIMIT {$start}, {$limit} ";
		
	$sql = sprintf($format, $table, $foreign_key, $id, $start, $limit);

	$res = db::execute($sql, array($id));
	if(is_array($res) && !empty($res)) {
		foreach($res as $k=>$v) {
			$res[$k]['ctime'] = date('Y-m-d H:i:s', $v['createtime']);
		}
	}
    return $res;
}

/**
 * 分页
 * @param string $url
 * @param int $total
 * @param int $page
 * @param int $limit
 * @return string pager
 */
function pager($url,$total,$page,$limit=20){
	$ceil = ceil($total/$limit);
	$ceil >1 && $ceil_limit=5;
	if($ceil >1 && $page>=5){
		$ceil_limit=10;
	}
	if($page>=8){
		$ceil-$page >10? $st=$page-5:$st=$ceil-10;
		$ceil_limit += $st-1;
		if($ceil - $page <8){
			$st = $page-2;
			$ceil_limit = $ceil;
		}
		if($ceil - $page ==10){
			$st = $page-2;
			$ceil_limit =$st+9;
		}
	}else {
		$st=1;
	}
	$ceil <$ceil_limit && $ceil_limit=$ceil;
	$spage = '';
	for ($st;$st<=$ceil_limit;$st++){
		if ($page == $st || (empty($page) && $page==$st-1)) {
			$page==0&&$page=1;
			$spage .="<font>[$page]</font>&nbsp;";
		}else
			$spage .= "<a rel='{$st}'><font>[$st]</font></a>&nbsp;";
	}

	if($page>=$ceil){
		$npage = "<font>[已到尾页]</font>";
	}else {
		$npage = "<a rel='".($page+1)."'>[下一页]</a>";
		$npage .= "<a rel='".$ceil."'>[到尾页]</a>";
	}
	$ppage = ($page>7) ? "<a rel='1'>[回首页]</a>" : '';
	return $ceil>1?$ppage.$spage.$npage:$spage;
}

function answer_is_right($answer, $cookiename) {
	if($_COOKIE[$cookiename]){
		$right= intval($_COOKIE[$cookiename]);
		$answer=intval($answer);
			if($right === $answer) return true;
		}else return false;
}

function not_empty($arr, $req) {
	foreach($arr as $v) {
		if(empty($req[$v])) return false;
		else continue;
	}
}

/*
 * 插入评论
*/
function insert_msg($table, $keyvalue, $answer, $cookiename) {
	
		if(!answer_is_right($answer, $cookiename)) return false;
		$value = array();
		$keys = $values = '';
		foreach($keyvalue as $k=>$v) {
			$value[] = strip_tags($v);
			$keys .= "`{$k}`, ";
			$values .= "?, ";
		}
		$keys = rtrim($keys, ', ');
		$values = rtrim($values, ', ');
			
		$prepare = "INSERT INTO {$table} ({$keys}) VALUES ($values)";
		$flag = db::execute($prepare, $value);	
		//echo json_encode(array('success'=>$flag, 'data'=>$value));
		exit;
}

?>